<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_product\Entity\ShusyProductStandard;
use Drupal\shusy_product_pintuan\Entity\ShusyProductPintuan;
use Drupal\shusy_product_pintuan\Entity\ShusyProductPintuanStandard;
use ServicesException;

/**
 * @OA\Schema(
 *   schema="StandardPt",
 *   type="object",
 *   description="StandardPt",
 *   allOf={
 *       @OA\Schema(ref="#/components/schemas/Standard"),
 *   }
 * )
 */
class StandardPt extends Standard {

  protected function setValue() {
    parent::setValue();
    if ($this->entity instanceof ShusyProductStandard) {
      $amount = $this->entity->amount;
      $es = shusy_product_pintuan_standard_load_multiple(FALSE, ['product_standard_id' => $this->entity->id]);
      if (!empty($es)) {
        $e = reset($es);
        if ($e instanceof ShusyProductPintuanStandard && $e->status == 1) {
          $ptProduct = $this->wrapper->product->pintuan->value();
          if ($ptProduct instanceof ShusyProductPintuan && $ptProduct->status == 1) {
            //拼团价格模式 0 跟随产品 1 固定金额 2 比例折扣
            switch ($e->amount_type) {
              case 0:
                //拼团价格模式 1 固定金额 2 比例折扣
                switch ($ptProduct->amount_type) {
                  case 1:
                    $amount -= $ptProduct->amount_1;
                    break;
                  case 2:
                    $amount = ($amount * (1 - $ptProduct->amount_2 / 10000));
                    break;
                }
                break;
              case 1:
                $amount -= $e->amount_1;
                break;
              case 2:
                $amount = ($amount * (1 - $e->amount_2 / 10000));
                break;
            }
            if ($amount < 0) {
              $amount = 0;
            }
            $value = [
              /**
               * @OA\Property(
               *   property="amount",
               *   type="number",
               *   description="拼团价格",
               * ),
               */
              'amount' => $this->convertYuan($amount),
            ];
            $this->merge($value);
            return;
          }
        }
      }
    }
    throw new ServicesException('未开启拼团');
  }
}
